# -- coding: utf-8 --
"""
# [Example] Miahx© 交互框架信息表示模型的 DDS 消息收发示例

**模块：MIAHX© / 框架基础服务层（FFST） / 交互框架信息表示模型（IFIRM）**

Version: 0.4.10,
Last updated: October 13, 2024

## Contributor(s)
* YAO Naiming <[naiming@iscas.ac.cn](mailto:naiming@iscas.ac.cn)>

## Change log
### v0.4.10
- .13: [更新] 适配新消息定义
- .9: [新增] packed 模式支持 timestamps 和 sns 字段 (deprecated)
### v0.4.7
- .24: [新增] 初始实现

---
Copyright © 2024-2025 MIAHX Contributors, ISCAS, and ASIC. All Rights Reserved.
Licensed under Apache-2.0.
"""

import threading
import time

from miahx_support.dds.fastdds import *
from miahx_support.stag import STag

import launcher


def bng_navigation_writer(p: Participant, e: threading.Event):
    stag = STag(**dict(sensor_channel=1, sensor_domain='CARRIER', sensor_type='VBNG_NAVIGATION',
                       sensor_channel_type='IGNORE', sensor_modality='POINT', sensor_data_format='CSV')).encode()
    writer = BngNavigationStreamWriter(p, stag=stag, srate=10, schns=['#7'])
    while not e.is_set():
        waypoints = [dict(distToTarget=1.0, pos=(1, 2, 3)),
                     dict(name='wp', distToTarget=1.0, pos=(1, 2, 3))]
        chunk = [(100, 12.23, dict(event=EBngNavigationEvent.TURN_RIGHT, distance=11, waypoints=waypoints), None),
                 (100, 12.23, dict(event=EBngNavigationEvent.MERGE_LANE_LEFT, distance=100), None)]
        writer.write(chunk, 0, 0)
        time.sleep(1)


def bng_navigation_reader(p: Participant, e: threading.Event):
    def on_data_available(data):
        hdr = data.header()
        dm = hdr.header().domain()
        src = hdr.header().source()
        prefix = f'[{dm}::{src}::{name}]'

        schns = tuple(hdr.schns())
        samples = list(data.samples())
        log.info(f'{prefix} stag = `{hdr.stag()}`')
        log.info(f'{prefix} srate = `{hdr.srate()}`')
        log.info(f'{prefix} schns = `{schns}`')
        log.info(f'{prefix} elements = [{len(samples)}]')

        for i, sample in enumerate(samples):
            log.info(f'{prefix} Element [{i}]:')

            route = sample.route()
            log.info(f'{prefix} \t\tevent = `{route.event()}`')
            log.info(f'{prefix} \t\tdistance = `{route.distance()}`')
            for k, wp in enumerate(route.waypoints()):
                log.info(f'{prefix} \t\t\t-------- [{k}]')
                log.info(f'{prefix} \t\t\twp.name = `{wp.name()}`')
                log.info(f'{prefix} \t\t\twp.dist = `{wp.dist()}`')
                log.info(f'{prefix} \t\t\twp.pos = `{tuple(wp.pos())}`')

            log.info(f'{prefix} End Element [{i}] --------')

        log.info(f'{prefix} ----------------')

    with BngNavigationStreamReader(p, on_data_listeners=[on_data_available]) as reader:
        name = type(reader).__name__
        log.success(f'[{name}] Topic: {reader.topic_name}')
        reader.wait(e)


if __name__ == '__main__':
    log = launcher.log
    event = threading.Event()
    participant = Participant()
    packed_data = False

    launcher.run(lambda: (event, [
        threading.Thread(target=bng_navigation_writer, args=(participant, event), daemon=False),
        threading.Thread(target=bng_navigation_reader, args=(participant, event), daemon=False),
    ]))
